package top.go2do.email.business.email.service;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import top.go2do.email.exception.EmailException;
import top.go2do.websiteNavigation.configProperties.EmailModuleConfig;

import java.util.concurrent.TimeUnit;

import static top.go2do.common.redis.RedisKey.getKeyEmailVerifyCode;
import static top.go2do.websiteNavigation.exception.EmailErrorCode.*;

@Service
public class EmailServiceImpl implements EmailService{

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private EmailModuleConfig moduleConfig;

    @Override
    public void sendVerificationCode(String email) {
        /**
         * step1: 判断Redis中是否存在该邮箱已发送的验证码，如果存在则提示稍后重试
         */
        String key = getKeyEmailVerifyCode(email);

        if (redisTemplate.hasKey(key)) {
            throw new EmailException(EMAIL_VERIFY_CODE_EXIST);
        }

        /**
         * step2: 生成验证码, 向目标邮箱email发送携带验证码的邮件
         */
        String code = RandomUtil.randomNumbers(moduleConfig.getRegisterCodeLength());
        Integer expireMinute = moduleConfig.getRegisterCodeExpireMINUTE();

        // TODO: 根据appId获取appName
        String appName = "LinkNest";
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject(appName + "注册");
        message.setText("您的验证码是：" + code + "，有效期为" + expireMinute + "分钟。");
        mailSender.send(message);

        /**
         * step3: 验证码保存到Redis中并设置过期时间
         */
        redisTemplate.opsForValue().set(key, code, expireMinute, TimeUnit.MINUTES);
    }

    @Override
    public void checkVerificationCode(String email, String code) {
        /**
         * step1: 判断Redis中是否存在该邮箱已发送的验证码，如果不存在则提示验证码已过期
         */
        String key = getKeyEmailVerifyCode(email);

        if (!redisTemplate.hasKey(key)) {
            throw new EmailException(EMAIL_VERIFY_CODE_EXPIRED);
        }

        /**
         * step2: 从Redis中取出该邮箱已发送的验证码，判断验证码是否一致，不一致则提示验证码错误
         */
        String redisCode = (String) redisTemplate.opsForValue().get(key);
        if (!redisCode.equals(code)) {
            throw new EmailException(EMAIL_VERIFY_CODE_ERROR);
        }
    }
}
